package org.jeecg.modules.appuser.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.entity.*;
import org.jeecg.modules.appuser.mapper.TbUserSqtMapper;
import org.jeecg.modules.appuser.service.*;
import org.jeecg.modules.appuser.util.TransferSQT;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: tb_user_sqt
 * @Author: jeecg-boot
 * @Date: 2020-05-18
 * @Version: V1.0
 */
@Service
public class TbUserSqtServiceImpl extends ServiceImpl<TbUserSqtMapper, TbUserSqt> implements ITbUserSqtService {

    @Autowired
    @Lazy(true)
    private ITbUserUpgradeConfigService tbUserUpgradeConfigService;

    @Autowired
    @Lazy(true)
    private ITbUserGameBuidingService tbUserGameBuidingService;

    @Autowired
    private ITbUserSqtDetailService tbUserSqtDetailService;

    @Autowired
    @Lazy(true)
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ITbUserIntegralDetailService tbUserIntegralDetailService;

    @Autowired
    private ITbUserNoticeService tbUserNoticeService;

    @Autowired
    private ITb_user_contributionService tb_user_contributionService;

    /**
     * 默认自动升1级
     *
     * @param user_id
     * @param type
     * @return
     */
    @Override
    public Result<?> upgradeGameBuilding(String user_id, Integer type) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);
        TbUserSqt tbUserSqt = this.baseMapper.selectOne(queryWrapper);

        TbUserGameBuiding tbUserGameBuiding = tbUserGameBuidingService.getOne(queryWrapper);
        //得到等级
        TbUserUpgradeConfig tbUserUpgradeConfig = tbUserUpgradeConfigService.getById(tbUserGameBuiding.getGrade());
        int sort = tbUserUpgradeConfig.getSort();
        QueryWrapper gradeQuyerWrapper = new QueryWrapper();
        gradeQuyerWrapper.eq("sort", sort + 1);
        gradeQuyerWrapper.eq("type", type);
        TbUserUpgradeConfig tbUserUpgradeConfigPlus = tbUserUpgradeConfigService.getOne(gradeQuyerWrapper);
        if (null != tbUserSqt) {
            //自己的资产
            BigDecimal bigDecimal = tbUserSqt.getBalance();
            int profitNumber = tbUserUpgradeConfigPlus.getProfitNumber();
            BigDecimal profitNumberDecimal = new BigDecimal(profitNumber);
            int flag = profitNumberDecimal.compareTo(bigDecimal);
            if (flag > 0) {
                return Result.ok("资金不足，努力赚钱吧!");
            }
            //更新用户SQT表
            BigDecimal newBalance = bigDecimal.subtract(profitNumberDecimal);
            tbUserSqt.setBalance(newBalance);
            //增加日志明细
            saveSqtDetail(tbUserSqt, profitNumberDecimal);
            //更新资产
            this.updateById(tbUserSqt);
            // 升级等级
            tbUserGameBuiding.setGrade(tbUserUpgradeConfigPlus.getId());
            tbUserGameBuidingService.updateById(tbUserGameBuiding);
            //升级完成后，判断 是否花费 一万的积分，上级 邀请人为代理. 如果是代理，邀请人充值，反218 贡献值
        //    upgradeAgentByCostsIntegral(tbUserSqt);

            return Result.ok("升级成功");
        }
        return Result.ok("升级失败");
    }

    private void upgradeAgentByCostsIntegral(TbUserSqt tbUserSqt) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", tbUserSqt.getUserId());
        queryWrapper.eq("from_type", PayTypeConstant.PAYFORM_EXCHANGE_BIZ_HOURS);
        //积分花费10000 升级为代理
        List<TbUserIntegralDetail> tbUserIntegralDetailList = tbUserIntegralDetailService.list(queryWrapper);
        BigDecimal total = new BigDecimal(0);
        if (null != tbUserIntegralDetailList && tbUserIntegralDetailList.size() > 0) {
            for (TbUserIntegralDetail tbUserIntegralDetail : tbUserIntegralDetailList) {
                BigDecimal balance = tbUserIntegralDetail.getBalance();
                total = total.add(balance);
            }
        }
        TbMnUser tbMnUser = tbMnUserService.getById(tbUserSqt.getUserId());
        if (total.compareTo(new BigDecimal(10000)) > 0) {

            if (tbMnUser.getIntegralAgent() == 0) {
                tbMnUser.setIntegralAgent(1);
                tbMnUserService.updateById(tbMnUser);
                //加入通知
                TbUserNotice tbUserNotice = new TbUserNotice();
                tbUserNotice.setNoticeContent(tbMnUser.getPhone() + "升级为代理");
                tbUserNotice.setNoticeTitle(DateUtil.now() + ":升级完成");
                tbUserNotice.setNoticeSendStatus("0");
                tbUserNotice.setUserId(tbMnUser.getId());
                tbUserNotice.setNoticeType("1");
                tbUserNoticeService.addUserNotice(tbUserNotice);
            }
        }
//        //查询邀请人，查询是否10个代理人，升级高级代理
//        String registerCode = tbMnUser.getRegisterCode();
//        upgradeAgent(tbMnUser, registerCode, 1, 2, "高级代理");
//
//        //查询邀请人，查询是否10个高级代理，升级城市合伙人
//        upgradeAgent(tbMnUser, registerCode, 2, 3, "城市合伙人");
    }

//    private boolean upgradeAgent(TbMnUser tbMnUser, String registerCode, Integer in_IntegralAgent, Integer out_integral_agent, String agent_name) {
//
//        QueryWrapper queryWrapper1 = new QueryWrapper();
//        queryWrapper1.eq("register_code", registerCode);
//        queryWrapper1.eq("integral_agent", in_IntegralAgent);
//        List<TbMnUser> tbMnUserList = tbMnUserService.list(queryWrapper1);
//        if (null != tbMnUserList && tbMnUserList.size() > 10) {
//            QueryWrapper queryWrapper2 = new QueryWrapper();
//            queryWrapper2.eq("invite_code", registerCode);
//            TbMnUser tbMnUser2 = tbMnUserService.getOne(queryWrapper2);
//            tbMnUser2.setIntegralAgent(out_integral_agent);
//            tbMnUserService.updateById(tbMnUser2);
//            //加入通知
//            TbUserNotice tbUserNotice = new TbUserNotice();
//            tbUserNotice.setNoticeContent(tbMnUser.getPhone() + "升级为" + agent_name);
//            tbUserNotice.setNoticeTitle(DateUtil.now() + ":升级完成");
//            tbUserNotice.setNoticeSendStatus("0");
//            tbUserNotice.setUserId(tbMnUser.getId());
//            tbUserNotice.setNoticeType("1");
//            tbUserNoticeService.addUserNotice(tbUserNotice);
//        }
//        return true;
//    }

    @Override
    public TbUserSqt getOneByUserId(String userId) {

        QueryWrapper gradeQuyerWrapper = new QueryWrapper();
        gradeQuyerWrapper.eq("user_id", userId);

        return this.getOne(gradeQuyerWrapper);
    }

    @Override
    public Result<?> giveFirstSQT(String user_id) {
        TbUserSqt tbUserSqt = getOneByUserId(user_id);
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("give_sqt");
        String num_str = "0";
        if (null != dictModelList && dictModelList.size() > 0) {
            num_str = dictModelList.get(0).getValue();
        }
        BigDecimal balance = tbUserSqt.getBalance();
        BigDecimal new_balance = balance.add(new BigDecimal(num_str));
        tbUserSqt.setBalance(new_balance);
        tbUserSqt.setUserId(user_id);
        if (saveSqtDetailIn(tbUserSqt, new BigDecimal(num_str))) {
            TbMnUser tbMnUser = tbMnUserService.getById(user_id);
            tbMnUser.setIsRewardSqt(1);
            if (tbMnUserService.updateById(tbMnUser)) {
                return Result.ok("赠送成功");
            }
        }
        return Result.error("赠送");
    }

    @Override
    public Result<?> transferSQT2Exchange(String user_id, String uid, String transferNum) {

        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(uid) || StringUtils.isEmpty(transferNum)) {
            return Result.error("参数错误");
        }
        TbUserSqt tbUserSqt = getOneByUserId(user_id);
        synchronized (tbUserSqt) {
            BigDecimal balance = tbUserSqt.getBalance();
            if (transferNum.equals("0")) {
                return Result.error("划转数量大于0");
            }

            BigDecimal transferBanlance = new BigDecimal(transferNum);
            if (transferBanlance.compareTo(balance) > 0) {
                return Result.error("余额不足");
            }
            //查询贡献度，1：1  划转
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", user_id);
            Tb_user_contribution tb_user_contribution = tb_user_contributionService.getOne(queryWrapper);
            BigDecimal contributionBigDecimal = new BigDecimal(tb_user_contribution.getContributionValue());
            if (contributionBigDecimal.compareTo(BigDecimal.ZERO) == 0) {

                return Result.error("贡献值不足");
            }
            if (transferBanlance.compareTo(contributionBigDecimal) > 0) {
                transferBanlance = contributionBigDecimal;

            }


            BigDecimal new_balance = balance.subtract(transferBanlance);
            // 划转sqt到交易所
            String resultData = TransferSQT.transferData(uid, transferNum);
            JSONObject jsonresponse = JSON.parseObject(resultData);
            if (null != jsonresponse) {
                String status = jsonresponse.getString("status");
                if (status.equals("SUCCEED")) {
                    TbUserSqtDetail tbUserSqtDetail = new TbUserSqtDetail();
                    tbUserSqtDetail.setPayFrom(PayTypeConstant.PAYFORM_TRANSFER);
                    tbUserSqtDetail.setPayType(PayTypeConstant.PAYTYPE_EXPEND);
                    tbUserSqtDetail.setPayNumber(transferBanlance);
                    tbUserSqtDetail.setUserId(tbUserSqt.getUserId());
                    tbUserSqtDetail.setSqtId(tbUserSqt.getId());
                    tbUserSqtDetail.setPayAfterNumber(new_balance);
                    tbUserSqtDetail.setUid(uid);
                    if (tbUserSqtDetailService.save(tbUserSqtDetail)) {
                        tbUserSqt.setBalance(new_balance);
                        if (updateById(tbUserSqt)) {
                            BigDecimal new_contributionBigDecimal = contributionBigDecimal.subtract(transferBanlance);
                            tb_user_contribution.setContributionValue(new_contributionBigDecimal.intValue());
                            tb_user_contributionService.updateById(tb_user_contribution);

                            return Result.ok(tbUserSqtDetail);
                        }
                    }
                } else {
                    return Result.error(jsonresponse.getString("errorMessage"));
                }
            }
        }
        return Result.error("划转失败");
    }

    private boolean saveSqtDetailByTransfer(TbUserSqt tbUserSqt, BigDecimal newBalance) {
        TbUserSqtDetail tbUserSqtDetail = new TbUserSqtDetail();
        tbUserSqtDetail.setPayFrom(PayTypeConstant.PAYFORM_TRANSFER);
        tbUserSqtDetail.setPayType(PayTypeConstant.PAYTYPE_EXPEND);
        tbUserSqtDetail.setPayNumber(newBalance);
        tbUserSqtDetail.setSqtId(tbUserSqt.getId());
        if (tbUserSqtDetailService.save(tbUserSqtDetail)) {
            if (updateById(tbUserSqt)) {
                return true;
            }
        }
        return true;
    }

    private boolean saveSqtDetailIn(TbUserSqt tbUserSqt, BigDecimal newBalance) {
        TbUserSqtDetail tbUserSqtDetail = new TbUserSqtDetail();
        tbUserSqtDetail.setPayFrom(PayTypeConstant.PAYFORM_GIVE_SQT);
        tbUserSqtDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
        tbUserSqtDetail.setPayNumber(newBalance);
        tbUserSqtDetail.setUserId(tbUserSqt.getUserId());
        tbUserSqtDetail.setSqtId(tbUserSqt.getId());
        tbUserSqtDetail.setPayAfterNumber(tbUserSqt.getBalance());
        if (tbUserSqtDetailService.save(tbUserSqtDetail)) {
            if (updateById(tbUserSqt)) {
                return true;
            }
        }

        return true;
    }

    private boolean saveSqtDetail(TbUserSqt tbUserSqt, BigDecimal profitNumberDecimal) {
        TbUserSqtDetail tbUserSqtDetail = new TbUserSqtDetail();
        tbUserSqtDetail.setPayFrom(PayTypeConstant.PAYFORM_UPGRAGE);
        tbUserSqtDetail.setPayType(PayTypeConstant.PAYTYPE_EXPEND);
        tbUserSqtDetail.setPayNumber(profitNumberDecimal);
        tbUserSqtDetail.setUserId(tbUserSqt.getUserId());
        tbUserSqtDetail.setSqtId(tbUserSqt.getId());
        if (tbUserSqtDetailService.save(tbUserSqtDetail)) {
            if (updateById(tbUserSqt)) {
                return true;
            }
        }

        return true;
    }
}
